//
//  CarPurchaseComputerViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/10/19.
//

import UIKit

class PurchaseCalcuViewController: BaseViewController {
    var tableView: BaseTableView!
    var model: CarDetailsContentModel!//model
    
    var whatsAppBtn: UIButton = {
        let tempBtn = UIButton()
        tempBtn.setup_image(image: UIImage.init(named: "whats_app"))
        tempBtn.isHidden = false
        return tempBtn
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.title = MMLocalizedString("car_shopping_calculator", comment: "购车计算器")
        self.navBar.wr_setBottomLineHidden(hidden: true)
        self.initTableView()
        self.initTabbarView()
        self.dealData()
        whatsAppBtn.addTarget(self, action: #selector(whatsAppBtnAction), for: .touchUpInside)
        self.view.addSubview(self.whatsAppBtn)
        self.addSnpLayout()

    }
    
    private func addSnpLayout(){
        self.whatsAppBtn.snp.makeConstraints { make in
            make.right.equalTo(-12)
            make.width.equalTo(34)
            make.height.equalTo(34)
            make.bottom.equalTo(-TabbarHeight - 60)
        }
    }
    
    func initTableView(){
        self.tableView = BaseTableView(frame: CGRect(x: 0, y: NavBarHight, width: kScreenWidth, height: kScreenHeight - TabbarHeight - NavBarHight), style: .grouped)
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 2
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.register(CarInfoTableViewCell.self, forCellReuseIdentifier: "CarInfoTableViewCell")
        self.tableView.register(ModeTableViewCell.self, forCellReuseIdentifier: "ModeTableViewCell")
        self.tableView.register(InterestRateTableViewCell.self, forCellReuseIdentifier: "InterestRateTableViewCell")//利率
        self.tableView.register(MonthlyPaymentCell.self, forCellReuseIdentifier: "MonthlyPaymentCell")
        self.tableView.register(DeadlineTableViewCell.self, forCellReuseIdentifier: "DeadlineTableViewCell")//期限
        self.tableView.register(BookingPayTableViewCell.self, forCellReuseIdentifier: "BookingPayTableViewCell")
        self.tableView.backgroundColor = .white
        self.view.addSubview(self.tableView)
        
       
//       self.tableView.tableFooterView = self.initTableFooterView()
    }
    
    @objc func whatsAppBtnAction(){
        var tempStr = self.model?.shareText ?? ""
        let phone = "85262501888"
        tempStr = tempStr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
        
        var tempUrl = "whatsapp://send?text=\(tempStr)"
        if (phone != "") {
            tempUrl = "whatsapp://send?phone=\(phone)&text=\(tempStr)"
        }
        guard let url = URL.init(string: tempUrl) else {
            return
        }
        
        if UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }else{//没安装WhatsApp
            var str = self.model?.shareText ?? ""
            str = str.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!//反编码，如果没有不成功
            let noTemUrl = "https://wa.me/85262501888?text=Hi!" + str
            
            guard let url = URL.init(string: noTemUrl) else {
                return
            }
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
    }
    
//    func initTableFooterView() ->UIView{
//        let bgView = UIView(frame: CGRect(x: 14, y: 10, width: kScreenWidth - 28, height: 150))
//        self.bgView.backgroundColor = UIColor(hex: 0xFFCC32,alpha: 0.15)
//        self.bgView.layer.cornerRadius = 8
//        self.bgView.clipsToBounds = true
//        self.contentView.addSubview(self.bgView)
//        
//        let contentLab = UILabel(frame: )
//        self.contentLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 12)
//        self.contentLab.textColor = Theme.titleLabColor
//        self.contentLab.numberOfLines = 0
//        self.contentLab.text = MMLocalizedString("more_details", comment: "以上供款计算只供参考，请联络Kool Car销售顾问了解有关最终之供款安排。")
//        self.bgView.addSubview(  self.contentLab)
//    }
//    
    
    func initTabbarView(){
        let tempH = 50 + IphoneXMarginBottom + (IphoneXMarginBottom > 1 ? 0 : 4)
        let bgView = UIView(frame: CGRect(x: 0, y: kScreenHeight - tempH, width: kScreenWidth, height: tempH))
        bgView.backgroundColor = .white
        self.view.addSubview(bgView)
        
        let sureBtn = UIButton(frame: CGRect(x: 14, y: 4 , width: kScreenWidth - 28, height: 46))
        sureBtn.backgroundColor = Theme.mainColor
        sureBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        sureBtn.layer.cornerRadius = 8
        sureBtn.clipsToBounds = true
        sureBtn.setTitleColor(.white, for: .normal)
        sureBtn.setTitle(MMLocalizedString("subscribe_now", comment: "立即订购"),for: .normal)
        sureBtn.addTarget(self, action: #selector(sureBtnAntion), for: .touchUpInside)
        bgView.addSubview(sureBtn)
    }

    
    
    func dealData(){
        self.model?.wayName = MMLocalizedString("prepaid_amount", comment: "预付金额")
        self.model?.reminder = MMLocalizedString("initial_period_explain", comment: "即您于签订合约时所缴付以降低贷款总额之金额。您的首期付款愈高，每月月费便愈低。")
        // 月供=(车辆售价*年利率/12)+(车辆售价/期数）
        let rate = (self.model?.interestRate ?? 0)! / 100
        self.model?.monthlyAmount = ((self.model?.price ?? 0) * rate / 12) + ((self.model?.price ?? 0) / 36)
                //首期金额=月供*【（期数/12）+1】
        let priceMon = (self.model?.monthlyAmount ?? 0) * Double((36 / 12 + 1))
        self.model?.firstAmount = priceMon
    }
    
    
    
    //MARK: - Antion
    @objc func sureBtnAntion(){
        if UserModule.shared.isLogined == false{
            self.jumpToLogin()
            return
        }
        
        if self.model == nil{
            return
        }
        //let vc = ReservedWheelViewController()
        let vc = VehicleInfoViewController()
        vc.contentModel = self.model
        self.navigationController?.pushViewController(vc, animated: true)
        //订购成功
//        vc.carOrderSucceedBlock = { [weak self] in
//
//        }
    }
    
    func jumpToLogin(){
        guard let tabbarVC = UIApplication.shared.keyWindow?.rootViewController as? BaseTabbarController else {
            return
        }
        let vc = LoginViewController()
        let loginNavi = BaseNavigationController.init(rootViewController: vc)
        loginNavi.modalPresentationStyle = .fullScreen
        tabbarVC.present(loginNavi, animated: true)
    }

}

extension PurchaseCalcuViewController : UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 5
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: "CarInfoTableViewCell", for: indexPath) as! CarInfoTableViewCell
            if self.model != nil{
                cell.setModel(model: self.model)
            }
            return cell
            
        case 1:
            let cell = tableView.dequeueReusableCell(withIdentifier: "ModeTableViewCell", for: indexPath) as! ModeTableViewCell
            cell.delegate = self
            return cell
            
        case 2:
            let cell = tableView.dequeueReusableCell(withIdentifier: "MonthlyPaymentCell", for: indexPath) as! MonthlyPaymentCell
            if self.model != nil{
                cell.setModel(model: self.model)
            }
            return cell
        case 3:
            let cell = tableView.dequeueReusableCell(withIdentifier: "InterestRateTableViewCell", for: indexPath) as! InterestRateTableViewCell
            cell.delegate = self
            if self.model != nil{
                cell.setContentModel(contentModel: self.model)
            }
            return cell
            
        case 4:
            let cell = tableView.dequeueReusableCell(withIdentifier: "DeadlineTableViewCell", for: indexPath) as! DeadlineTableViewCell
            cell.delegate = self
            return cell
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: "BookingPayTableViewCell", for: indexPath) as! BookingPayTableViewCell
            if self.model != nil{
                cell.setModel(model: self.model)
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 6 {
            return 50
        }
        return 0.01
    }
    
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let bgView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 0.01))
        bgView.backgroundColor = .white
        return bgView
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let bgView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 0.01))
        bgView.backgroundColor = .clear
        return bgView
    }
   
}

//选择方式
extension PurchaseCalcuViewController: ModeTableViewCellDelegate{
    func modeTableViewCelldidSelect(index: NSInteger) {
        if index == 0{
            self.model?.wayName = MMLocalizedString("prepaid_amount", comment: "预付金额")
            self.model?.interestRate = 3.75
            
        }else{
            self.model?.wayName = MMLocalizedString("first_issue", comment: "首期")
          
            self.model?.interestRate = 4.75
        }
        self.model.selectType = index
        self.dealPriceData()
        self.tableView.reloadData()
    }
    
    func dealPriceData(){
        switch self.model?.selectType {//租赁供款
        case 0:
            // 月供=(车辆售价*年利率/12)+(车辆售价/期数）
            let rate = (self.model?.interestRate)! / 100
            self.model?.monthlyAmount = ((self.model?.price ?? 0) * rate / 12) + ((self.model?.price ?? 0) / (self.model?.deadlines ?? 36))
            //首期金额=月供*【（期数/12）+1】
            self.model?.firstAmount = (self.model?.monthlyAmount ?? 0) * Double((self.model?.deadlines ?? 36) / 12 + 1)
        default://租购供款
            //首期金额=车辆售价*10%
            self.model?.firstAmount = (self.model.price ?? 0) * 0.10
            // 借款=车辆售价*90%
            let borrowMoney = (self.model?.price ?? 0) * 0.9
            //月供=(借款*年利率/12)+(借款/期数）】
            let rate = (self.model?.interestRate)! / 100
            let priceMon = (borrowMoney * rate / 12) + (borrowMoney / (self.model?.deadlines ?? 36))
            self.model?.monthlyAmount = priceMon
        }
    }
    
}

//年利率
extension PurchaseCalcuViewController: InterestRateTableViewCellDelegate{
    func selectInterestRate(rate: Double) {
        self.view.endEditing(true)
        self.dealPriceData()
        self.tableView.reloadData()
    }
}


//贷款期数
extension PurchaseCalcuViewController: DeadlineTableViewCellDelegate{
    func selectDeadline(deadlines: Int) {
        self.model?.deadlines = deadlines
        self.dealPriceData()
        self.tableView.reloadData()
    }
    
}

